package com.ruoyi.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.info.DataPackageInfo;
import org.apache.commons.io.IOUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DataPackageParserUtil {
    private static final String MODULE_JSON_FILE = "modules.json";

    /**
     * 解析输入流中的压缩包信息
     */
    public static DataPackageInfo parse(InputStream zipStream) throws IOException {
        if (zipStream == null) {
            throw new IllegalArgumentException("输入流不能为空");
        }

        // 使用BufferedInputStream确保mark/reset支持
        try (BufferedInputStream bis = new BufferedInputStream(zipStream);
             ZipInputStream zis = new ZipInputStream(bis)) {

            // 验证ZIP文件格式
            if (!isValidZip(bis)) {
                throw new IOException("文件不是有效的ZIP格式或已损坏");
            }

            return parseZipContent(zis);
        }
    }

    /**
     * 验证是否为有效的ZIP文件
     */
    private static boolean isValidZip(BufferedInputStream bis) throws IOException {
        bis.mark(4);
        byte[] signature = new byte[4];
        int read = bis.read(signature);
        bis.reset();

        return read == 4 &&
                signature[0] == 0x50 && signature[1] == 0x4B &&
                signature[2] == 0x03 && signature[3] == 0x04;
    }

    /**
     * 解析ZIP内容
     */
    private static DataPackageInfo parseZipContent(ZipInputStream zis) throws IOException {
        ZipEntry entry;
        DataPackageInfo result = null;
        boolean found = false;

        while ((entry = zis.getNextEntry()) != null) {
            String entryName = entry.getName();

            if (entry.isDirectory()) {
                continue;
            }

            // 获取文件名（忽略路径）
            String fileName = getFileNameFromPath(entryName);

            if (MODULE_JSON_FILE.equals(fileName)) {
                String jsonStr = IOUtils.toString(zis, StandardCharsets.UTF_8);
                result = parseToDataPackageInfo(jsonStr);
                found = true;
                break;
            }
        }

        if (!found) {
            throw new IllegalArgumentException("压缩包中未找到 " + MODULE_JSON_FILE);
        }

        return result;
    }

    /**
     * 从路径中提取文件名
     */
    private static String getFileNameFromPath(String path) {
        if (path == null || path.isEmpty()) {
            return path;
        }

        int lastSeparator = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
        if (lastSeparator != -1 && lastSeparator < path.length() - 1) {
            return path.substring(lastSeparator + 1);
        }
        return path;
    }
    private static DataPackageInfo parseToDataPackageInfo(String jsonStr) {
        JSONObject root = JSON.parseObject(jsonStr);
        DataPackageInfo info = new DataPackageInfo();

        // 解析基础信息
        JSONObject app = root.getJSONObject("app");
        info.setBundleName(app.getString("bundleName"));
        info.setVendor(app.getString("vendor"));

        // 处理版本信息
        JSONObject version = app.getJSONObject("version");
        info.setVersionCode(version.getString("code"));
        info.setVersionCodeNum(version.getString("name"));

        return info;
    }


}
